const fp = require('fastify-plugin');
const moment = require('moment');
const _ = require('lodash');

module.exports = fp(
  function(fastify, opts, next) {
    const scheduleJob = _.get(fastify, 'utils.scheduleJobs');
    const db = _.get(fastify, 'db');
    const { date_format } = _.get(fastify, 'utils.constants');

    if (!(scheduleJob && db)) {
      console.error('定时任务或者数据库错误');
      process.exit(1);
    }

    let instance_id = process.env.INSTANCE_ID;
    if (instance_id === '0') {
      const jobName = `实例${instance_id} 统计每日实时数据`;
      scheduleJob.perMinutes({ minutes: 10, jobName }, function() {
        const now = moment();
        const [hour, minute] = [now.hour(), now.minutes()];

        const date = hour == 0 && minute < 10 ? now.subtract(1, 'day').format(date_format) : now.format(date_format);
        db.analysisActions(date);
        db.analysisArenaSeason(date);
      });

      db.analysisActions(moment().format(date_format));
      db.analysisArenaSeason(moment().format(date_format));
    }

    next();
  },
  {
    fastify: '1.7.0',
  }
);
